package com.renaud.tvSpy.menu;

import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;

import javax.swing.ButtonGroup;
import javax.swing.JMenu;
import javax.swing.JMenuBar;
import javax.swing.JMenuItem;
import javax.swing.JRadioButtonMenuItem;

import com.renaud.tvSpy.VideoDevice;
import com.renaud.tvSpy.View;




public class MyMenu {
	private JMenuBar menu;
	private JMenu devices;
	private JMenu affichage;
	private JMenuItem read;
	private View view;

	private JMenu tailleEcran;
	
	
	



	public MyMenu(View view){
		this.view = view;
		this.menu = new JMenuBar();
		this.devices = new JMenu("Devices");
		this.affichage = new JMenu("Affichage");
		this.menu.add(this.devices);
		this.menu.add(this.affichage);
		
		
		this.readMenu();
		this.scaleMenu();
		
	}

	
	
	
	public void addDevice(final VideoDevice d){
		final String id = d.getDeviceId();
		JMenuItem item = new JMenuItem(id);
		devices.add(item);
		
		final View v = this.view;

		item.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				v.setActiveDevice(d);
			}
		});
	}
	
	
	
	


	public JMenuBar getMenu() {
		return menu;
	}

	private void scaleMenu(){
		this.tailleEcran = new JMenu("Scale");
		ButtonGroup bg = new ButtonGroup();
		
		this.addNewScale(bg,0.1f);
		this.addNewScale(bg,0.2f);
		this.addNewScale(bg,0.3f).setSelected(true);
		this.addNewScale(bg,0.6f);
		this.addNewScale(bg,0.8f);
		
		this.affichage.add(this.tailleEcran);
	}
	
	private JRadioButtonMenuItem addNewScale(ButtonGroup bg,final float scale){
		JRadioButtonMenuItem item = new JRadioButtonMenuItem(String.valueOf(scale));
		bg.add(item);
		this.tailleEcran.add(item);
		
		final View v = this.view;
		item.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				v.resetScale(scale);
			}
		});
		
		return item;
	}
	
	
	
	
	

	private void readMenu(){
		this.read = new JMenuItem("Stop");
	
		this.devices.add(this.read);
		this.devices.addSeparator();
		
		final View v = this.view;
		this.read.addActionListener(new ActionListener() {
			
			@Override
			public void actionPerformed(ActionEvent e) {
				JMenuItem item = (JMenuItem) e.getSource();
				if(v.isReading()){
					v.stopReading();
					item.setText("Start");
				}else{
					v.startReading();
					item.setText("Stop");
				}
				
				
			}
		});
	}
	
}
